<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI简历助手</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .chat-container {
            max-width: 800px;
            margin: 30px auto;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        .chat-header {
            background-color: #3f51b5;
            color: white;
            padding: 15px;
            text-align: center;
            position: relative;
        }
        .chat-body {
            height: 500px;
            padding: 20px;
            overflow-y: auto;
            background-color: #fff;
        }
        .message {
            margin-bottom: 15px;
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 18px;
            clear: both;
        }
        .user-message {
            float: right;
            background-color: #e3f2fd;
            border-bottom-right-radius: 0;
        }
        .ai-message {
            float: left;
            background-color: #f1f1f1;
            border-bottom-left-radius: 0;
        }
        .file-upload-area {
            text-align: center;
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 5px;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .file-upload-area:hover {
            border-color: #3f51b5;
            background-color: #f9f9f9;
        }
        .typing-indicator {
            display: inline-block;
            padding: 10px;
        }
        .typing-dot {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #999;
            margin-right: 3px;
            animation: typingAnimation 1.4s infinite ease-in-out;
        }
        @keyframes typingAnimation {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-5px); }
        }
        .error-message {
            color: #dc3545;
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 10px;
            border-radius: 5px;
        }
        .file-info {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        .loading-spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-left-color: #3f51b5;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 新增状态栏样式 */
        .user-status {
            position: absolute;
            top: 15px;
            right: 15px;
            z-index: 1000;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #fff;
            color: #3f51b5;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .dropdown-menu {
            min-width: 200px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border: none;
            padding: 10px 0;
        }
        .dropdown-item {
            padding: 8px 20px;
            color: #333;
            transition: all 0.2s;
        }
        .dropdown-item:hover {
            background-color: #f5f5f5;
            color: #3f51b5;
        }
        .dropdown-divider {
            margin: 5px 0;
        }
        .user-info {
            padding: 10px 20px;
            font-size: 14px;
            color: #666;
        }
        .user-name {
            font-weight: bold;
            color: #333;
        }
        /* 新增评分按钮样式 */
        .result-btn-container {
            text-align: center;
            margin: 15px 0;
        }
        .result-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }
        .result-btn:hover {
            background-color: #45a049;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .result-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
    </style>
    <!-- 引入pdf.js相关库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
</head>
<body>
<div class="container">
    <div class="chat-container">
        <!-- 新增用户状态栏 -->
        <div class="user-status">
            <div class="dropdown">
                <div class="user-avatar dropdown-toggle" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="fa fa-user"></i>
                </div>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                    <li class="user-info">
                        <div class="user-name">当前用户</div>
                        <div sec:authentication="name">用户名</div>
                    </li>
                    <li><hr class="dropdown-divider"></li>
                    <!-- 只有管理员才能看到用户管理链接 -->
                    <li sec:authorize="hasRole('ADMIN')">
                        <a class="dropdown-item" href="/manager">
                            <i class="fa fa-users"></i> 用户管理
                        </a>
                    </li>
                    <li><a class="dropdown-item" href="#"><i class="fa fa-cog"></i> 个人设置</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="/logout"><i class="fa fa-sign-out"></i> 退出登录</a></li>
                </ul>
            </div>
        </div>

        <div class="chat-header">
            <h3>AI简历评分系统</h3>
            <p>你提供简历，我来评分</p>
        </div>
        <div class="chat-body" id="chatBody">
            <div class="message ai-message">
                您好！我是AI简历评分系统，上传您的简历，我可以尝试解析并分析内容，并帮您评分～
            </div>
        </div>
        <div class="chat-footer p-3 bg-light">
            <div class="file-upload-area" id="fileUploadArea">
                <i class="fa fa-cloud-upload fs-1"></i>
                <p>点击或拖拽上传PDF文件</p>
                <input type="file" id="uploadFile" accept=".pdf" style="display: none;">
            </div>
            <div class="result-btn-container">
                <button class="result-btn" id="viewResultBtn" disabled>查看评分结果</button>
            </div>
            <div class="input-group">
                <input type="text" class="form-control" id="userInput" placeholder="输入您的问题...">
                <button class="btn btn-primary" id="sendButton">发送</button>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // DeepSeek API配置 - 请替换为您的实际有效API密钥（需具备对应权限）
        const DEEPSEEK_API_KEY = 'sk-9483d697aaa0459591f6116e2c930265';
        const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'; // 确保是正确的API地址

        // DOM元素
        const chatBody = document.getElementById('chatBody');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        const fileUploadArea = document.getElementById('fileUploadArea');
        const uploadFile = document.getElementById('uploadFile');
        const viewResultBtn = document.getElementById('viewResultBtn');
        let pdfTextContent = ''; // 存储解析出的PDF文本内容

        // 显示消息
        function appendMessage(content, isUser = false) {
            const msgDiv = document.createElement('div');
            msgDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
            msgDiv.innerHTML = content;
            chatBody.appendChild(msgDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
        }

        // 显示错误
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'message error-message';
            errorDiv.textContent = message;
            chatBody.appendChild(errorDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
        }

        // 显示打字状态
        function showTyping() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message ai-message typing-indicator';
            typingDiv.innerHTML = `
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            `;
            chatBody.appendChild(typingDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
            return typingDiv;
        }

        // 显示加载 spinner
        function showLoading() {
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'message ai-message loading-spinner-container';
            loadingDiv.innerHTML = '<div class="loading-spinner"></div><p>努力思考中...</p>';
            chatBody.appendChild(loadingDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
            return loadingDiv;
        }

        // 真正解析PDF文件（使用pdf.js）
        function parseRealPdfFile(file) {
            return new Promise((resolve, reject) => {
                const fileReader = new FileReader();
                fileReader.onload = function() {
                    const typedArray = new Uint8Array(this.result);
                    pdfjsLib.getDocument(typedArray).promise.then(pdf => {
                        let totalPages = pdf.numPages;
                        let pagesText = [];
                        let loadedPages = 0;

                        for (let i = 1; i <= totalPages; i++) {
                            pdf.getPage(i).then(page => {
                                page.getTextContent().then(textContent => {
                                    let pageText = textContent.items.map(item => item.str).join(' ');
                                    pagesText.push(pageText);
                                    loadedPages++;

                                    if (loadedPages === totalPages) {
                                        const fullText = pagesText.join('\n');
                                        resolve({
                                            name: file.name,
                                            size: file.size,
                                            content: fullText
                                        });
                                    }
                                }).catch(err => {
                                    reject(err);
                                });
                            }).catch(err => {
                                reject(err);
                            });
                        }
                    }).catch(err => {
                        reject(err);
                    });
                };
                fileReader.onerror = function() {
                    reject(new Error('文件读取失败'));
                };
                fileReader.readAsArrayBuffer(file);
            });
        }

        // 调用DeepSeek API
        async function callDeepSeekAPI(prompt) {
            const typingIndicator = showTyping();
            let loadingIndicator = null;

            try {
                // 构建提示信息，结合PDF内容（如果有）
                let fullPrompt = prompt;
                if (pdfTextContent) {
                    fullPrompt = `PDF内容：${pdfTextContent}\n\n用户问题：${prompt}\n\n请基于PDF内容回答，若没有关联，也可正常回答。`;
                }

                setTimeout(() => {
                    if (typingIndicator && typingIndicator.parentNode) {
                        typingIndicator.parentNode.removeChild(typingIndicator);
                    }
                    loadingIndicator = showLoading();
                }, 800);

                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: "你是和DeepSeek一样智能的助手，具备丰富知识和强大推理能力，能友好、专业地回答各类问题，包括基于PDF内容的分析。"
                            },
                            {
                                role: "user",
                                content: fullPrompt
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 1500
                    })
                });

                if (loadingIndicator && loadingIndicator.parentNode) {
                    loadingIndicator.parentNode.removeChild(loadingIndicator);
                }
                if (typingIndicator && typingIndicator.parentNode) {
                    typingIndicator.parentNode.removeChild(typingIndicator);
                }

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error?.message || `HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                const aiResponse = data.choices[0].message.content;
                appendMessage(aiResponse.replace(/\n/g, '<br>'));

            } catch (error) {
                if (loadingIndicator && loadingIndicator.parentNode) {
                    loadingIndicator.parentNode.removeChild(loadingIndicator);
                }
                if (typingIndicator && typingIndicator.parentNode) {
                    typingIndicator.parentNode.removeChild(typingIndicator);
                }

                showError(`请求失败: ${error.message}`);
                console.error("DeepSeek API错误:", error);
            }
        }

        // 处理用户消息
        async function handleUserMessage() {
            const message = userInput.value.trim();
            if (message) {
                appendMessage(message, true);
                userInput.value = '';
                await callDeepSeekAPI(message);
            }
        }

        // PDF文件上传处理
        uploadFile.addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (file && file.name.endsWith('.pdf')) {
                appendMessage(`正在解析PDF文件: ${file.name}`, true);
                try {
                    const pdfData = await parseRealPdfFile(file);
                    pdfTextContent = pdfData.content;
                    appendMessage(`PDF文件 ${file.name} 解析完成，可提问相关问题～`, false);
                    // 启用查看评分结果按钮
                    viewResultBtn.disabled = false;
                    // 保存简历内容到localStorage
                    localStorage.setItem('resumeContent', pdfTextContent);
                } catch (error) {
                    showError(`PDF解析失败: ${error.message}`);
                }
            } else {
                showError('请上传PDF格式的文件');
            }
        });

        // 点击上传区域触发文件选择
        fileUploadArea.addEventListener('click', () => {
            uploadFile.click();
        });

        // 拖拽上传
        fileUploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileUploadArea.style.borderColor = '#3f51b5';
            fileUploadArea.style.backgroundColor = '#f0f7ff';
        });

        fileUploadArea.addEventListener('dragleave', () => {
            fileUploadArea.style.borderColor = '#ccc';
            fileUploadArea.style.backgroundColor = '';
        });

        fileUploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            fileUploadArea.style.borderColor = '#ccc';
            fileUploadArea.style.backgroundColor = '';

            if (e.dataTransfer.files.length) {
                const file = e.dataTransfer.files[0];
                if (file.name.endsWith('.pdf')) {
                    uploadFile.files = e.dataTransfer.files;
                    uploadFile.dispatchEvent(new Event('change'));
                } else {
                    showError('请上传PDF格式的文件');
                }
            }
        });

        // 查看评分结果按钮点击事件
        viewResultBtn.addEventListener('click', function() {
            if (pdfTextContent) {
                window.location.href = 'result.html';
            }
        });

        // 事件监听
        sendButton.addEventListener('click', handleUserMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') handleUserMessage();
        });
    });

</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
